package com.quick.android.adapter;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

/**
 * 对于BaseAdapter的基本封装
 *
 * @param <T>
 * @author quick
 */
public abstract class BaseListAdapter<T> extends BaseAdapter {
    private Activity mContext;
    private LayoutInflater mInflater;
    private List<T> data;

    public BaseListAdapter(Activity context) {
        mContext = context;
        mInflater = LayoutInflater.from(mContext);
    }

    /**
     * 重置数据
     *
     * @param list
     */
    public void resetData(final List<T> list) {
        mContext.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                data.addAll(list);
                notifyDataSetChanged();
            }
        });
    }

    /**
     * 添加数据
     *
     * @param list
     */
    public void addData(final List<T> list) {
        mContext.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (data == null) {
                    data = list;
                } else {
                    data.addAll(list);
                }
                notifyDataSetChanged();
            }
        });
    }

    /**
     * 清空当前数据
     */
    public void clearData() {
        mContext.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (data != null) {
                    data.clear();
                }
                notifyDataSetChanged();
            }
        });
    }

    @Override
    public int getCount() {
        return data == null ? 0 : data.size();
    }

    @Override
    public T getItem(int position) {
        return data == null ? null : data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        convertView = bindView(mInflater);
        T item = getItem(position);
        bindData(position, item);
        return convertView;
    }

    /**
     * 綁定Item布局
     */
    public abstract View bindView(LayoutInflater inflater);

    /**
     * 设置数据
     */
    public abstract void bindData(int position, T item);
}
